package com.zhao.dota.security;

import com.zhao.dota.bo.AuthenticateUser;

import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.LinkedHashMap;
import java.util.Map;

public class AuthenticationKeyGenerator {

    public String extractKey(AuthenticateUser authentication) {
        Map<String, Object> values = new LinkedHashMap<>();
        values.put("id", authentication.getId());
        if (authentication.getOpenId() != null) {
            values.put("openId", authentication.getOpenId());
        }
        if (authentication.getUnionId() != null) {
            values.put("unionId", authentication.getUnionId());
        }
        return generateKey(values);
    }

    protected String generateKey(Map<String, ?> values) {
        MessageDigest digest;
        try {
            digest = MessageDigest.getInstance("MD5");
            byte[] bytes = digest.digest(values.toString().getBytes(StandardCharsets.UTF_8));
            return String.format("%032x", new BigInteger(1, bytes));
        } catch (NoSuchAlgorithmException nsae) {
            throw new IllegalStateException("MD5 algorithm not available.  Fatal (should be in the JDK).", nsae);
        }
    }

}
